import base64
from Crypto.Cipher import DES
from Crypto.Util.Padding import pad, unpad

"DES 的key, iv 为八位"


def des_encrypt(key, iv, text):
    """
    先将字节填充，再加密，再转base64
    :param key:
    :param iv:
    :param text:
    :return:
    """
    cipher = DES.new(key, DES.MODE_CBC, iv)
    cipher_text = cipher.encrypt(pad(text, DES.block_size))
    return base64.b64encode(cipher_text).decode()


def des_decrypt(key, iv, cipher_text):
    """
    先密文base64解码，再解密，再去除填充
    :param key:
    :param iv:
    :param cipher_text:
    :return:
    """
    cipher = DES.new(key, DES.MODE_CBC, iv)
    decrypt_text = unpad(cipher.decrypt(base64.b64decode(cipher_text)), DES.block_size)
    return decrypt_text.decode()


if __name__ == '__main__':
    key = b'01234567'
    iv = b'abcdefgh'
    text = '今天是星期一'.encode()
    cipher_text = des_encrypt(key, iv, text)
    print(cipher_text)
    decrypt_text = des_decrypt(key, iv, cipher_text)
    print(decrypt_text)
